/*------------------------------|
|	NyaomiLoader		|
|	ver 0.1			|
|	By: TheOnlyJoey		|
|				|
\-------------------------------/
*/
#include "main.h"
#include "gamelibrary.h"
#include "ikarusdebug.h"

const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;
bool FULLSCREEN = true;

//The surfaces that will be used
SDL_Surface *picture = NULL;
SDL_Surface *background = NULL;
SDL_Surface *screen = NULL;
SDL_Surface *header = NULL;
SDL_Surface *footer = NULL;
SDL_Surface *text = NULL;

SDL_Event event;
SDL_Joystick *stick = NULL;

TTF_Font *font12, *font20 = NULL;
SDL_Color textColor = { 255, 255, 255 };

SDL_Surface *load_image( std::string filename )
{
    //Temporary storage for the image that's loaded
    SDL_Surface* loadedImage = NULL;

    //The optimized image that will be used
    SDL_Surface* optimizedImage = NULL;

    //Load the image
    loadedImage = IMG_Load( filename.c_str() );

    //If nothing went wrong in loading the image
    if( loadedImage != NULL )
    {
        //Create an optimized image
        optimizedImage = SDL_DisplayFormat( loadedImage );

        //Free the old image
        SDL_FreeSurface( loadedImage );
    }

    //Return the optimized image
    return optimizedImage;
}

MainClass::MainClass()
{
	GameLibrary* gamelibrary = new GameLibrary();
}

void apply_surface( int x, int y, SDL_Surface* source, SDL_Surface* destination )
{
    //Make a temporary rectangle to hold the offsets
    SDL_Rect offset;

    //Give the offsets to the rectangle
    offset.x = x;
    offset.y = y;

    //Blit the surface
    SDL_BlitSurface( source, NULL, destination, &offset);
}

void InitSDL()
{
    //Initialize all SDL subsystems
	if (SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
	{
	printf("Can not Init SDL\n");
	}

	//Set up the screen
	SDL_WM_SetCaption( "NyaomiLoader ver 0.1", NULL );
	if (FULLSCREEN == false)
		screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_HWSURFACE );
	else
		screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_HWSURFACE | SDL_NOFRAME );

	//If there was an error in setting up the screen
	if( screen == NULL )
	{
	printf("Screen is NULL\n");
	}
	//Initialize SDL_ttf
	if( TTF_Init() == -1 )
	{
	printf("TTF is NULL\n");
	}
	//Check if there's any joysticks 
	if( SDL_NumJoysticks() < 1 ) 
	{ 
	printf("No Joysticks Found");
	} 
	//Open the joystick 
	stick = SDL_JoystickOpen( 0 ); 
	//If there's a problem opening the joystick 
	if( stick == NULL ) 
	{ 
	printf("There is a problem opening the joystick");
	}
}

void MainClass::LoadData()
{
	GameLibrary* gamelibrary = new GameLibrary();
	font12 = TTF_OpenFont( "fonts/Averia-Regular.ttf", 12 );
	if (font12 == NULL)
		printf("Font Averia-Regular.tff not found\n");
	font20 = TTF_OpenFont( "fonts/Averia-Bold.ttf", 20 );
	if (font20 == NULL)
		printf("Font Averia-Regular.tff not found\n");

	background = load_image( "background.png" );
	if (background == NULL)
		printf("Background Not Found\n");
	
	picture = load_image( "gamepics/" + gamelibrary->Games.find(SelectedGame)->second.second );
	if (picture == NULL)
		printf("picture Not Found\n");
	dprintf("Test: %s \n", gamelibrary->Games.find(SelectedGame)->second.second.c_str());
	
}

bool UpdateScreen()
{
    if( SDL_Flip( screen ) == -1 )
    {
        return 1;
    }
}

void DrawSurfaces()
{
	apply_surface( 0,0, background, screen);
	apply_surface( 40, 40, picture, screen );
	apply_surface( 240, 5, header, screen );
	apply_surface( 500, 465, footer, screen );
	apply_surface( 5, 465, text, screen );
}

void MainClass::ChangeGameBack(bool ChangeGameBack)
{
	GameLibrary* gamelibrary = new GameLibrary();
	SDL_FillRect( screen, 0, 0 );
	SDL_FreeSurface( picture );
	if (ChangeGameBack == true)
		SelectedGame--;
	else if (ChangeGameBack == false)
		SelectedGame++;
	
	if (SelectedGame <= 0)
		SelectedGame = gamelibrary->Games.size();
	else if (SelectedGame == gamelibrary->Games.size()+1)
		SelectedGame = 1;
	
	std::string bcfolder("gamepics/");
	std::string currentgamepic(bcfolder + gamelibrary->Games.find(SelectedGame)->second.second.c_str());

	dprintf("Changed Game to: %i \n", SelectedGame);
	
	dprintf("Test: %s \n", currentgamepic.c_str());
	picture = load_image( currentgamepic );
	
	std::string gametext1("Current Game: ");
	std::string gametext(gametext1 + gamelibrary->Games.find(SelectedGame)->second.first.c_str());
	text = TTF_RenderText_Blended(font12, gametext.c_str(), textColor);
	dprintf("Game Changed\n");
	
	DrawSurfaces();
	UpdateScreen();
}

void MainClass::StartGame()
{
	GameLibrary* gamelibrary = new GameLibrary();
	std::string execute("sh ./scripts/");
	std::string exfile(execute + gamelibrary->Games.find(SelectedGame)->second.first.c_str() + ".sh");
	system( exfile.c_str() );
	dprintf("%s.sh\n", gamelibrary->Games.find(SelectedGame)->second.first.c_str());
}

int main( int argc, char* args[] )
{
	GameLibrary gamelibrary;
	MainClass* mc = new MainClass();
	bool quit = false;

	mc->SelectedGame = 1;
	int lastaxisX;

	InitSDL();

	mc->LoadData();
	dprintf("maintest: %s.sh\n", gamelibrary.Games.find(mc->SelectedGame)->second.first.c_str());
	dprintf("Size of gamemap: %i \n", gamelibrary.Games.size());
	//Draw the Menu text
	footer = TTF_RenderText_Blended(font12, "Rev 0.2 by TheOnlyJoey", textColor);
	header = TTF_RenderText_Blended(font20, "Nyaomi Game Loader", textColor);
	std::string gametext1("Current Game: ");
	std::string gametext(gametext1 + gamelibrary.Games.find(mc->SelectedGame)->second.first.c_str());
	text = TTF_RenderText_Blended(font12, gametext.c_str(), textColor);

	//Apply the picture to the screen
	DrawSurfaces();
	//Update the screen
    	UpdateScreen();

	while( quit == false )
	{
	SDL_Delay(1);
	//If there's an event to handle
	if( SDL_PollEvent( &event ) )
	{
	    //If a key was pressed
	    if( event.type == SDL_KEYDOWN )
	    {
		switch( event.key.keysym.sym )
		{
		    case SDLK_UP: printf("Pressed Up\n"); break;
		    case SDLK_DOWN: printf("Pressed Down\n"); break;
		    case SDLK_LEFT: mc->ChangeGameBack(true); break;
		    case SDLK_RIGHT: mc->ChangeGameBack(false); break;
		    case SDLK_c: mc->StartGame(); break;
		    case SDLK_q: system("quadrapassel"); break;
		    case SDLK_ESCAPE: quit = true;
		}
	    }
	    if ( event.type == SDL_JOYAXISMOTION )
	    {
	     	if ( event.jaxis.axis == 0 )
	     	{
	     		if( ( event.jaxis.value != -32768 ) && ( event.jaxis.value != 32767 ) ) 
	     		{
	     			lastaxisX = SDL_JoystickGetAxis(stick, 0);
	     			printf("SDL_JoystickGetX = %i\n", lastaxisX);
	     		}
			else 
				if( event.jaxis.value == -32768 ) 
				{
					if(event.jaxis.value - lastaxisX <= -200){
						lastaxisX=event.jaxis.value;
					mc->ChangeGameBack(false);}
				}
				if( event.jaxis.value == 32767 )
				{
					if(event.jaxis.value - lastaxisX >= 200){
						lastaxisX=event.jaxis.value;
					mc->ChangeGameBack(true);}
				}
		}
	    }
	    if ( event.type == SDL_JOYBUTTONDOWN )
	    {
	   	if (event.jbutton.button == 0)
	   	{
	   		mc->StartGame();
	   	}
	    }
	    else if( event.type == SDL_QUIT )
	    {
		quit = true;
	    }
	}
	}

	//Cleanup
	SDL_FreeSurface( picture );
	SDL_FreeSurface( background );
	SDL_FreeSurface( header );
	SDL_FreeSurface( footer );
	SDL_FreeSurface( text );
	SDL_FreeSurface( screen );
	SDL_JoystickClose( stick );

	TTF_CloseFont(font12);
	TTF_CloseFont(font20);
	TTF_Quit();
	SDL_Quit();

	return 0;
}
